package com.sx.shop.controller;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.sx.shop.entity.*;
import com.sx.shop.service.UserService;
import com.sx.shop.vo.ResultVo;

import javax.servlet.http.HttpSession;
import java.util.UUID;

@Controller
public class UserController {
	
	// DI 依赖注入
	@Autowired
	private UserService userService;
	@RequestMapping("/")
	public String index(){
		return "login";
	}
	@RequestMapping(value = {"/login"})
	public String toLogin(){
		return "login";
	}
	@RequestMapping("/index")
	public String toIndex(){
		return "index";
	}
	//@RequestMapping(value = "/index" method="get")
	//指定请求方式
	@GetMapping("/user/index")
	public String openPage() {
		//这是一个html页面
		return "user";
	}
	
	
	/* 获取用户列表数据 */
	@GetMapping(value = "/user/list")
	@ResponseBody//只返回数据不找页面
	public ResultVo selectUser(String keyword ,Integer page , Integer limit){
		//Ioc 控制反转
		//UserService service=new UserService();
		return userService.selectUser(keyword,page, limit);
	}
	@ResponseBody
	@PostMapping(value="/user/save")
	public void saveUser(User user) {
		userService.doSave(user);
	}
	
	
	@ResponseBody
	@PostMapping(value="/user/del")
	public void delUser(@RequestParam(value = "id"/* ,required = false */) Integer userid) {
		userService.doDel(userid);
	}
	
	
	@ResponseBody
	@GetMapping(value = "/user/{id}")
	public User selectUserById(@PathVariable("id") Integer id) {
	
		return 	userService.selectUserById(id);			
	}
	@RequestMapping("/user/login")
	@ResponseBody
	public Boolean login(String username, String password, HttpSession session)
	{
		//  System.out.println("login");
		if(username==null||password==null)
		{
			return false;
		}
		if(username==""||password=="")
		{
			return false;
		}
		//获取当前用户
		Subject subject= SecurityUtils.getSubject();
		//封装用户登录数据
		try{
			UsernamePasswordToken token = new UsernamePasswordToken(username,password);
			subject.login(token);//执行登录，如果没有异常 就可以
			session.setAttribute("username",username);
			User u = userService.findByUserName(username);
			session.setAttribute("role",u.getRole());
			System.out.println(session.getAttribute("username"));
			return true;
		}catch (UnknownAccountException e)//用户名不存在
		{
			session.setAttribute("msg","用户名错误");
			//model.addAttribute("msg","用户名错误");
			return false;
		}catch (IncorrectCredentialsException e)//密码错误
		{
			session.setAttribute("msg","密码错误！");
			// model.addAttribute("msg","密码错误");
			return false;
		}
	}
	@RequestMapping("/user/register")
	@ResponseBody
	public String register(String username,String password,String name,Integer sex, HttpSession session)
	{

		if(username==null||sex==null)
		{
			return "信息不全，注册失败";
		}
		String pwd=password;

		//生成uuid
		String salt = UUID.randomUUID().toString();
        /*
        MD5加密:
        *使用SimpleHash类对原始密码进行加密。
        *第一个参数代表使用MD5方式加密 第二个参数为原始密码
        *第三个参数为盐值，即用户名第四个参数为加密次数
            *最后用toHex()方法将加密后的密码转成String*/
		String newPwd=new SimpleHash("MD5",pwd,salt,1024).toHex();
		User user=userService.findByUserName(username);
		if(user==null)
		{
			userService.register(username,newPwd,salt,sex,"0",name);
//			session.setAttribute("msg","注册成功请登录！");
			return "注册成功!请登录";
		}else{
//			session.setAttribute("msg","用户名已存在！");
//			return "redirect:/login.html";
			return "用户名已存在";

		}
	}
	@RequestMapping("/user/logout")
	public String logout(HttpSession session){
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return "redirect:/login.html";
	}
}
